<!-- src/views/Login.vue -->
<template>
  <div class="w-full max-w-md mx-auto">
    <!-- 登录卡片 -->
    <div class="bg-white rounded-xl card-shadow p-8 relative overflow-hidden">
      <!-- 装饰元素 -->
      <div class="absolute -right-10 -top-10 w-40 h-40 bg-primary/5 rounded-full"></div>
      <div class="absolute -left-16 -bottom-16 w-48 h-48 bg-primary/5 rounded-full"></div>

      <!-- 登录标题 -->
      <div class="text-center mb-8 relative">
        <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-neutral-700 mb-2">临巴堤防工程管理系统</h1>
        <p class="text-neutral-400 text-sm">请登录以访问系统</p>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="login" class="space-y-5 relative">
        <!-- 用户名输入 -->
        <div class="space-y-2">
          <label for="username" class="block text-sm font-medium text-neutral-600">用户名</label>
          <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                            <i class="fa fa-user"></i>
                        </span>
            <input
                type="text"
                id="username"
                v-model="form.username"
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-200 bg-white text-neutral-700 input-focus transition-all duration-300"
                placeholder="请输入用户名"
                required
            >
          </div>
        </div>

        <!-- 密码输入 -->
        <div class="space-y-2">
          <label for="password" class="block text-sm font-medium text-neutral-600">密码</label>
          <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                            <i class="fa fa-lock"></i>
                        </span>
            <input
                type="password"
                id="password"
                v-model="form.password"
                class="w-full pl-10 pr-10 py-3 rounded-lg border border-neutral-200 bg-white text-neutral-700 input-focus transition-all duration-300"
                placeholder="请输入密码"
                required
            >
            <button
                type="button"
                @click="togglePasswordVisibility"
                class="absolute inset-y-0 right-0 flex items-center pr-3 text-neutral-400 hover:text-neutral-600 transition-colors"
            >
              <i :class="passwordVisible ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
            </button>
          </div>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="bg-danger/10 border border-danger/20 rounded-lg p-3 text-danger text-sm">
          <i class="fa fa-exclamation-circle mr-2"></i>
          {{ errorMessage }}
        </div>

        <!-- 登录按钮 -->
        <button
            type="submit"
            class="w-full bg-primary hover:bg-secondary text-white font-medium py-3 px-4 rounded-lg transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center"
            :disabled="loading"
        >
          <span v-if="!loading">登录</span>
          <span v-else class="flex items-center">
                        <i class="fa fa-circle-o-notch fa-spin mr-2"></i>
                        登录中...
                    </span>
        </button>
      </form>

      <!-- 底部信息 -->
      <div class="mt-8 pt-6 border-t border-neutral-100 text-center">
        <p class="text-neutral-400 text-xs">© 2025 贵州中致城建设工程有限公司 | 技术支持: 138-8315-5245</p>
      </div>
    </div>

    <!-- 令牌信息显示 -->
    <div v-if="tokenInfo" class="mt-6 bg-white rounded-xl card-shadow p-6">
      <h3 class="text-lg font-semibold text-neutral-700 mb-4">令牌信息</h3>
      <div class="space-y-3 text-sm">
        <div class="flex justify-between">
          <span class="text-neutral-500">访问令牌:</span>
          <span class="font-medium text-neutral-700 truncate max-w-[200px]">{{ tokenInfo.access_token.substring(0, 20) }}...</span>
        </div>
        <div class="flex justify-between">
          <span class="text-neutral-500">令牌类型:</span>
          <span class="font-medium text-neutral-700">{{ tokenInfo.token_type }}</span>
        </div>
        <div class="flex justify-between">
          <span class="text-neutral-500">有效期:</span>
          <span class="font-medium text-neutral-700">{{ formatExpiresIn(tokenInfo.expires_in) }}</span>
        </div>
        <div class="flex justify-between">
          <span class="text-neutral-500">权限范围:</span>
          <span class="font-medium text-neutral-700">{{ tokenInfo.scope }}</span>
        </div>
      </div>

      <!-- JWT 解码信息 -->
      <div class="mt-4 pt-4 border-t border-neutral-100">
        <h4 class="text-sm font-medium text-neutral-600 mb-2">JWT 内容</h4>
        <pre class="bg-neutral-100 rounded-lg p-3 text-xs text-neutral-600 overflow-x-auto max-h-40">{{ decodedToken }}</pre>
      </div>

      <!-- 复制和退出按钮 -->
      <div class="mt-4 flex space-x-3">
        <button
            @click="copyToken"
            class="flex-1 bg-neutral-100 hover:bg-neutral-200 text-neutral-700 py-2 px-4 rounded-lg transition-colors text-sm flex items-center justify-center"
        >
          <i class="fa fa-copy mr-2"></i>复制令牌
        </button>
        <button
            @click="logout"
            class="flex-1 bg-danger/10 hover:bg-danger/20 text-danger py-2 px-4 rounded-lg transition-colors text-sm flex items-center justify-center"
        >
          <i class="fa fa-sign-out mr-2"></i>退出登录
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import router from "@/router/index.js";

// 表单数据
const form = reactive({
  username: '123',
  password: '123',
});

// 状态
const loading = ref(false);
const errorMessage = ref('');
const tokenInfo = ref(null);
const decodedToken = ref('');
const passwordVisible = ref(false);

// API 配置
const apiConfig = {
  baseURL: `${import.meta.env.VITE_APP_API_BASE_URL}/apis`,
  tokenEndpoint: '/oauth/token',
  /*baseURL: 'http://192.168.1.245:8083',
  tokenEndpoint: '/oauth/token',*/
};

// 登录方法
const login = async () => {
  // 重置状态
  errorMessage.value = '';
  loading.value = true;

  try {
    // 构建请求数据
    const formData = new URLSearchParams();
    formData.append('grant_type', 'password');
    formData.append('client_id', 'ZhuangjiWebApp');
    formData.append('client_secret', 'ZhuangjiWebApp');
    formData.append('username', form.username);
    formData.append('password', form.password);

    // 发送请求
    const response = await axios.post(
        `${apiConfig.baseURL}${apiConfig.tokenEndpoint}`,
        formData,
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        }
    );

    // 保存令牌信息
    tokenInfo.value = response.data;

    // 解码 JWT
    decodeJwt(response.data.access_token);

    // 存储令牌到本地存储
    localStorage.setItem('access_token', response.data.access_token);
    localStorage.setItem('refresh_token', response.data.refresh_token);


    // 显示成功消息（实际项目中可跳转至首页）
    console.log('登录成功:', response.data);
    //实际项目中可跳转至首页
    router.push("/")

  } catch (error) {
    // 处理错误
    console.error('登录失败:', error);

    if (error.response) {
      // 服务器返回错误响应
      errorMessage.value = error.response.data.error_description || '认证失败，请检查用户名和密码';
    } else if (error.request) {
      // 请求已发送但无响应
      errorMessage.value = '无法连接到服务器，请检查网络连接';
    } else {
      // 请求设置时出错
      errorMessage.value = '请求配置错误: ' + error.message;
    }
  } finally {
    loading.value = false;
  }
};

// 解码 JWT
const decodeJwt = (token) => {
  try {
    // JWT 由三部分组成：header.payload.signature
    const parts = token.split('.');
    if (parts.length !== 3) {
      throw new Error('无效的 JWT 格式');
    }

    // 解码 payload（base64 解码）
    const payload = JSON.parse(atob(parts[1]));
    decodedToken.value = JSON.stringify(payload, null, 2);

    localStorage.setItem('user_name', payload.user_name);
    console.log("用户名"+localStorage.getItem('user_name'));
  } catch (error) {
    console.error('解码 JWT 失败:', error);
    decodedToken.value = '无法解码 JWT: ' + error.message;
  }
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value;
};

// 复制令牌到剪贴板
const copyToken = () => {
  if (tokenInfo.value) {
    navigator.clipboard.writeText(tokenInfo.value.access_token)
        .then(() => {
          alert('令牌已复制到剪贴板');
        })
        .catch(err => {
          console.error('复制失败:', err);
          alert('复制失败，请手动复制');
        });
  }
};

// 退出登录
const logout = () => {
  tokenInfo.value = null;
  decodedToken.value = '';
  localStorage.removeItem('access_token');
  localStorage.removeItem('refresh_token');
};

// 格式化有效期
const formatExpiresIn = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`;
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`;
  } else {
    return `${seconds}秒`;
  }
};

// 检查本地存储中是否有令牌
onMounted(() => {
  const savedToken = localStorage.getItem('access_token');
  if (savedToken) {
    tokenInfo.value = {
      access_token: savedToken,
      token_type: 'bearer',
      expires_in: 7200, // 默认2小时
      scope: 'all',
    };
    decodeJwt(savedToken);
  }
});

</script>

<style scoped>
/* 可选：添加局部样式，注意避免影响全局Tailwind类 */
</style>